package thread.commucation;

//测试生产者消费者-> 利用缓冲区解决：管程法
//生产者、消费者、产品、缓冲区
public class TestPC {

    public static void main(String[] args) {
        SyncArea syncArea = new SyncArea();

        new Productor(syncArea).start();
        new Consumer(syncArea).start();
    }
}

class Productor extends Thread{
    SyncArea syncArea = new SyncArea();

    public Productor(SyncArea syncArea){
        this.syncArea = syncArea;
    }

    //生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            syncArea.push(new Product(i));
            System.out.println("生产了" + i);
        }
    }
}

class Consumer extends Thread{

    SyncArea syncArea = new SyncArea();

    public Consumer(SyncArea syncArea){
        this.syncArea = syncArea;
    }

    //消费
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了" + syncArea.pop().id);

        }
    }
}

class Product{
    int id;

    public Product(int id){
        this.id = id;
    }
}

class SyncArea{
    //容器大小
    Product[] products = new Product[10];

    //容器计数器
    int count = 0;

    //生产者放入产品
    public synchronized void push(Product product){
        //如果容器满了，等待消费者消费
        if(count == products.length){
            //通知消费者消费，生产者等待
            try{
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //没满，加入产品
        products[count] = product;
        count++;

        //通知消费者消费
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Product pop(){
        //如果容器为空，等待生产者生产
        if (count == 0){
            try{
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //消费者消费

        count--;
        Product product = products[count];
        //通知生产者生产
        this.notifyAll();

        return product;

    }



}


